package cn.com.pansky.action.homePage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import lss.socialsecurity.card.ejb.web12333.SSCWEB12333Port;
import lss.socialsecurity.card.ejb.web12333.SSCWEB12333_Impl;
import lss.socialsecurity.card.valueobject.PSSC110;
import lss.socialsecurity.card.valueobject.RSSC110;
import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.sql.Model;
import net.vsame.url2sql.utils.PostParam;
import cn.com.pansky.action.imgContrast.ImgContrast;
import cn.com.pansky.action.logs.Log;
import cn.com.pansky.helper.PostHelper;
import cn.com.pansky.service.CommonService;
import cn.com.pansky.util.ByteToImageUtil;
import cn.com.pansky.util.LssConstant;
import cn.com.pansky.util.CodeUtil;

import com.alibaba.fastjson.JSONObject;

/**
 * 我要认证
 * 
 * @author 王润华
 *
 */
public class AuthenticationAction extends CommonAction {
	private Log log = new Log();
	private CommonService cs = new CommonService();
	
	// 社保卡接口
	private static SSCWEB12333_Impl service;
	private static SSCWEB12333Port port;

	private ByteToImageUtil byteToImageUtil = new ByteToImageUtil();

	/**
	 * 验证是否有认证资格 TODO 接口有修改
	 */
	public void isNeedAuth() {
		List<PostParam> params = new ArrayList<PostParam>();
		PostParam AAC002 = new PostParam("AAC002", "string", getCA006ByCA001());// 身份证号
		PostParam AAC003 = new PostParam("AAC003", "string", getCA003ByCA001());// 姓名
		params.add(AAC002);
		params.add(AAC003);
		JSONObject results = PostHelper.send("auth/isNeedAuth.json", params);
		boolean isRetired = (Boolean) results.get("isRetired");
		boolean isAuthed = (Boolean) results.get("isAuthed");
		datas.put("isPass", false);
		if (isRetired == true && isAuthed == false) {
			datas.put("isPass", true);
		}
		context.getDatas().put("result", datas);
	}

	public void authentication() {
		String CA001 = getParam("CA001");
		//日志记录start
		String AF001 = log.start(CA001, "RZ");
		// 获取刷脸图片
		String imgPath = getParam("img");
		Properties p = new Properties();
		try {
			p.load(getClass().getClassLoader().getResourceAsStream(
					"config.properties"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		Model model = SqlHelper
				.queryOne(
						"select CA006 from RC03 where CA001 = ?",
						CA001);
		
		String filePath = p.getProperty("imgPath");
		// 指定身份证照片保存路径：
		String filename = filePath + CA001 + ".jpg";
		
		try {
			System.out.println("开始调用社保卡接口获取照片：");
			service = new SSCWEB12333_Impl(CodeUtil.WSURL);
			System.out.println("调用社保卡接口结束");
		} catch (IOException e1) {
			datas.put("isPass", false);
			datas.put("info", "获取社保卡照片异常，请联系管理员！");
			context.getDatas().put("result", datas);
			return;
		}
		port = service.getSSCWEB12333Port();
		PSSC110 pssc110 = new PSSC110();
		pssc110.setAAC002(model.getString("CA006"));
		pssc110.setAAE011(user.getString("AA001"));
		pssc110.setAAE036("");
		// 返回查询结果
		RSSC110 rs = null;
		try {
			rs = port.sSC110(pssc110);
		} catch (RemoteException e1) {
			datas.put("isPass", false);
			datas.put("info", "获取社保卡照片异常，请联系管理员！");
			context.getDatas().put("result", datas);
			return;
		}
		if (rs.getBAZ150() == null || "".equals(rs.getBAZ150())) {
			// 拿到实名认证身份证照片：
			cs.getIdcardPic(CA001, filename);
		} else {
			byteToImageUtil.byte2image(rs.getBAZ150(), filename);
		}
		
		// 调用照片比对方法，比对刷脸与身份证照
		double num = ImgContrast.imgContrast(filename, imgPath);
		if (0.0 == num) {
			datas.put("isPass", false);
			datas.put("info", "身份证上人脸照片模糊，无法识别特征！");
			context.getDatas().put("result", datas);
			return;
		}

		List<PostParam> param = new ArrayList<PostParam>();
		PostParam AAC002 = new PostParam("AAC002", "string", getCA006ByCA001());// 身份证号
		PostParam AAC003 = new PostParam("AAC003", "string", getCA003ByCA001());// 姓名
		PostParam BIC110 = new PostParam("BIC110", "string",
				String.valueOf(num));// 相似度
		InputStream in = null;
		try {
			in = new FileInputStream(imgPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		param.add(new PostParam("img", null, "17.sdc", in));
		param.add(AAC002);
		param.add(AAC003);
		param.add(BIC110);
		PostParam BIC101 = null;
		try {
			if (num > LssConstant.CONFIDENCE) {
				// 更新本地特征
				String findRC06 = urlConfig.getVar("findRC06");
				Model m = SqlHelper.queryOne(findRC06, CA001);
				// 判断库中是否有这个人的特征信息：
				String id = "";
				if (m != null) {
					id = m.getString("CA011");
				}
				cs.isnertRC06(imgPath, CA001, num, id);

				BIC101 = new PostParam("BIC101", "string", "1");// 认证成功
				datas.put("isPass", true);
			} else {
				BIC101 = new PostParam("BIC101", "string", "0");// 认证失败
				datas.put("isPass", false);
			}
			param.add(BIC101);
			PostHelper.send("auth/add.json", param);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			// 将身份证临时照片删除
			File file = new File(filename);
			file.delete();
			// 将我要认证刷脸图片删除
			File file2 = new File(imgPath);
			file2.delete();
		}
		
		//日志记录end
		boolean result = log.end(AF001, datas.get("isPass"), " ");
		System.out.println("日志：认证"+result);
		
		context.getDatas().put("result", datas);

	}
	
	/**
	 * 认证使用社保卡
	 */
	public void authentication_new() {
		String CA001 = getParam("CA001");
		// 获取质量最佳的人脸图片
		String imageBestPath = getParam("image_best");
		// 获取用作云端假脸攻击判定的照片
		String imageEnvPath = getParam("image_env");
		// 用于校验上传数据的校验字符串
		String delta = getParam("delta");

		Properties p = new Properties();
		try {
			p.load(getClass().getClassLoader().getResourceAsStream(
					"config.properties"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		Model model = SqlHelper
				.queryOne(
						"select CA006 from RC03 where CA001 = ?",
						CA001);
		
		String sicardfilePath = p.getProperty("imgPath")
				+ model.getString("CA006") + ".jpg";

		try {
			System.out.println("开始调用社保卡接口获取照片：");
			service = new SSCWEB12333_Impl(CodeUtil.WSURL);
			System.out.println("调用社保卡接口结束");
		} catch (IOException e1) {
			datas.put("isPass", false);
			datas.put("info", "获取社保卡照片异常，请联系管理员！");
			context.getDatas().put("result", datas);
			return;
		}
		port = service.getSSCWEB12333Port();
		PSSC110 pssc110 = new PSSC110();
		pssc110.setAAC002(model.getString("CA006"));
		pssc110.setAAE011(user.getString("AA001"));
		pssc110.setAAE036("");
		// 返回查询结果
		RSSC110 rs = null;
		try {
			rs = port.sSC110(pssc110);
		} catch (RemoteException e1) {
			datas.put("isPass", false);
			datas.put("info", "获取社保卡照片异常，请联系管理员！");
			context.getDatas().put("result", datas);
			return;
		}
		if (rs.getBAZ150() == null || "".equals(rs.getBAZ150())) {
			// 拿到实名认证身份证照片：
			cs.getIdcardPic(CA001, sicardfilePath);
		} else {
			byteToImageUtil.byte2image(rs.getBAZ150(), sicardfilePath);

			// 调用照片比对方法，比对刷脸与身份证照
			JSONObject result = ImgContrast.imgCompare(sicardfilePath, imageBestPath,
					imageEnvPath, delta);
			
			if (!"0".equals(result.getString("code"))) {
				datas.put("isPass", true);
				datas.put("info", "认证失败！");
				context.getDatas().put("result", datas);
				return;
			}
			Double num = result.getDouble("confidence");
			List<PostParam> param = new ArrayList<PostParam>();
			PostParam AAC002 = new PostParam("AAC002", "string",
					getCA006ByCA001());// 身份证号
			PostParam AAC003 = new PostParam("AAC003", "string",
					getCA003ByCA001());// 姓名
			PostParam BIC110 = new PostParam("BIC110", "string", String
					.valueOf(num));// 相似度
			InputStream in = null;
			try {
				in = new FileInputStream(imageBestPath);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			param.add(new PostParam("img", null, "17.sdc", in));
			param.add(AAC002);
			param.add(AAC003);
			param.add(BIC110);
			PostParam BIC101 = null;
				if (num > LssConstant.CONFIDENCE) {
					// 更新本地特征
					String findRC06 = urlConfig.getVar("findRC06");
					Model m = SqlHelper.queryOne(findRC06, CA001);
					// 判断库中是否有这个人的特征信息：
					String id = "";
					if (m != null) {
						id = m.getString("CA011");
					}
					try {
						cs.isnertRC06(imageBestPath, CA001, num, id);
					} catch (Exception e) {
						datas.put("isPass", false);
						datas.put("info", "数据保存失败，请联系管理员！");
						context.getDatas().put("result", datas);
						return;
					}
					BIC101 = new PostParam("BIC101", "string", "1");// 认证成功
					
					datas.put("isPass", true);
					datas.put("info", "认证成功！");
				} else {
					BIC101 = new PostParam("BIC101", "string", "0");// 认证失败
					datas.put("isPass", false);
					datas.put("info", "认证失败！");
				}
				param.add(BIC101);
				PostHelper.send("auth/add.json", param);

		}
		context.getDatas().put("result", datas);
	}
}
